<?php

namespace Home\Controller;
use Home\Org\Util\Sqlserver;
use Home\Org\Util\SalesSupervisor;

use Home\Org\Util\GtBuyer;

/**
 * 备货单
 * @author dem
 *
 */
class StockingController extends HomeController {

    private $theNormalReviewStep = 'wendy.li';
    private $theNormalReviewStepHighLevel = 'mario.wu';
    private $theGM = 'andy.fang';
    private $theFinance = 'melody.wang';
    private $theBoss = 'tony';

    //baden team
    private $specialBadenChenTeam = array('mani.xie','sara.chen','lucy.yan','kevin.hu');
    private $theBaden = array('baden.chen');
    
    function index(){
        $this->display('Report/index');
    }
    
    function add(){
        $this->display();
    }
    
    
    
    function supplierselect(){
        $this->display();
    }
    
    function getsuppliersDataBySap(){
      
            import("@.ORG.Util.Sqlserver");
            $sqlObj  = new Sqlserver();
            $key = I('key');
            $where = " and frozenFor='N' ";
            //$where = "";
            if($key){
                $key = iconv('utf-8', 'GBK', $key);
                $where = " and frozenFor='N' and  cardName like '%{$key}%'";
            }
             $sql = "select cardcode,cardName ,CntctPrsn,phone1,phone2,MailAddres from ocrd where CardType='s'  $where ";
            //echo $sql;die();
             $res = $sqlObj->query($sql);
            $data = array('total'=>count($res),'data'=>$res);
            echo json_encode($data);
            exit;
        
    }
    
    function  clonedata(){
        $id = I('id');
        $list = D('StockingInfo')->where("stocking_id={$id}")->select();
        $this->assign("data",json_encode($list,JSON_UNESCAPED_UNICODE));
        $info = D('Stocking')->where("id={$id}")->find();
        $this->assign("stockingID",$id);
        $this->assign("info",$info);
        $this->display('clone');
    }

    function getCloneDetailData(){
        $id = $_REQUEST['id'];
        $list = M('StockingInfo')->where("stocking_id={$id}")->select();
        $data = array('total'=>count($list),'data'=>$list);
        echo json_encode($data);
    }
    
    
    function delete(){
        $id = (int)I('id');
        $res =  D('Stocking')->where("id={$id}")->delete();
        $res+=  D('StockingInfo')->where("stocking_id={$id}")->delete();
        echo $res;exit;
        
        
    }
    
    function save(){

        // 准备数据
        $respons = array('code'=>0,'msg'=>'操作成功!');
        $post = $_POST['data'];
        $type = I('type');
        $cp   = I('cp');
        $suppliers_code = I('gys_code');
        $suppliers_name= I('gys_name');
        $remarkes = I('remarkes');
        $storage_time = I('storage_time');
        $receipter = I('receipter');
        $receipterCode = I('receipterCode');

        // 基本验证
        if(!$post){
            $respons['code']=-1;
            $respons['msg']='数据错误';
            echo json_encode($respons);
            exit ;
        }

        // 验证供应商信息
        if($suppliers_code == $suppliers_name)
        {
            $respons['code']=-1;
            $respons['msg']='供应商信息错误！请使用系统提供的供应商查询功能！';
            echo json_encode($respons);
            exit ;
        }

        // 验证到货时间
        if(strtotime($storage_time)<time()){
            $respons['code']=-1;
            $respons['msg']='到货时间错误';
            echo json_encode($respons);
            exit ;
        }

        $id   = I('id');
        $model = D("Stocking");
        $infoModel = D("StockingInfo");
        $saveData = json_decode($post,true);

        // 验证仓库信息
        /*foreach ($saveData as $key=>$vo){
            $ckeck =$this->_checkItemWHCode($vo['item_code'], $vo['warehouse']);
            error_log($ckeck);
            if(!$ckeck){
                $respons['code']=-1;
                $respons['msg']=$vo['item_code'].' 仓库选择错误,请修改';
                echo json_encode($respons);
                exit ;
            }
        }*/

        // 汇总计算
        $total = array_sum(array_column($saveData, 'amout')); //备货物料总数量
        $totalPrice = array_sum(array_column($saveData, 'total_price')); //备货物料总价
        $user = session('user_name');
        $name = $user.'-'.time();
        $stock_process = array();
        $stock_process[] =$cp;
        // <- 以上基本数据准备完成.

        // 审批流判断开始 ->
        $runProcessTag = 0; // 0 : 不需要审批(默认), 1 : 要审批
        $items = array();
        $nowTime = date('Y-m-d H:i:s');
        $yesterdayTime = date('Y-m-d H:i:s',strtotime('-1 day'));

        // 审批流公共部分
        import("@.ORG.Util.GtBuyer");
        $gtBuyer = GtBuyer::getInstance();
        // 根据提交的$cp查找经理，并拼接审批流
        $theCaptain = $gtBuyer->getAllCaptain($cp,1);
        if($theCaptain){
            $stock_process[] = $theCaptain;
        }

        // 审批流特殊部分，拼接特殊人物：总监($totalPrice>100000)
        /*
        if($totalPrice>=100000)
        {
            $theCaptain = $gtBuyer->getAllCaptain($cp,2);
            if($theCaptain){
                $stock_process[] = $theCaptain;
            }
            $runProcessTag = 1;
        }else{
            // 非常规：需要判断“新品”(previous_price == 0)
            if($type == 2){
                // do loop
                foreach ($saveData as $key=>$vo){
                    if($vo['previous_price']==0)
                    {
                        $theCaptain = $gtBuyer->getAllCaptain($cp,2);
                        if($theCaptain){
                            $stock_process[] = $theCaptain;
                        }
                        $runProcessTag = 1;
                        break;
                    }
                }
            }
        }
        */
        $theCaptain = $gtBuyer->getAllCaptain($cp,2);
        if($theCaptain){
            $stock_process[] = $theCaptain;
        }
        $theCaptain = $gtBuyer->getAllCaptain($cp,3);
        if($theCaptain){
            $stock_process[] = $theCaptain;
        }

        // 审批流特殊部分，拼接特殊人物：wendy.li
        $stock_process[] = $this->theNormalReviewStep;

        // 审批流特殊部分，拼接特殊人物：mario($totalPrice>200000)
        if($totalPrice>=200000)
        {
            $stock_process[] = $this->theNormalReviewStepHighLevel;
            $runProcessTag = 1;
        }

        // 审批流特殊部分，拼接特殊人物：andy.fang($totalPrice>300000)
        if($totalPrice>=300000)
        {
            $stock_process[] = $this->theGM;
        }else{
            if($total>=2000)
            {
                $stock_process[] = $this->theGM;
                $runProcessTag = 1;
            }
        }

        // 审批流特殊部分，拼接特殊人物：tony($totalPrice>500000)
        if($totalPrice>=500000)
        {
            $stock_process[] = $this->theBoss;
        }else{
            if($total>=2000)
            {
                $stock_process[] = $this->theBoss;
            }
        }

        // 最终审批权：集采
        if($type == 1){
            // 审批流特殊部分，拼接特殊人物：melody.wang
            $stock_process[] = $this->theFinance;
        }else{

        }

        // 自动审批：必须是常规备货 $type == 3
        if ($type == 3 && $runProcessTag == 0) {
            foreach ($saveData as $key => $value){
                $itemCode = $value['item_code'];
                $itmeInformation = $this->_getItemInfo($itemCode);
                $suppliersCode = $value['suppliers_code'];

                // 0. 第一次采购必审批
                if ($itmeInformation['previous_price'] == 0)
                {
                    // must
                    //var_dump('must 01');
                    $runProcessTag = 1;
                    //break;
                }

                // 3. by 物料 判定条件: 小于等于上次采购价格.
                if ($value['p_price']>$itmeInformation['previous_price'])
                {
                    // must
                    //var_dump('must 02');
                    $runProcessTag = 1;
                }

                $items[$itemCode]['available_inventory'] = $itmeInformation['available_inventory']; //可用库存数量available_inventory
                $items[$itemCode]['r_inventory'] = $itmeInformation['r_inventory']; //安全库存
            }

//             2. by 物料 判定条件: 本次采购数量amout(post)+可用库存数量available_inventory(last code)+以当前时间为基准前溯过去24内订单数量总和sql 小于等于安全库存r_inventory(last code).
            if($runProcessTag == 0){

                foreach ($saveData as $key => $value){
                    $itemCode = $value['item_code'];
                    $suppliersCode = $value['suppliers_code'];
                    $itemAmount = $value['amout']; //本次采购数量amout

                    //使用缓存数据 $items
                    //查询think_stocking_info表中数据并判断
                    //think_stocking_info表中创建新字段 ALTER TABLE `think_stocking_info` ADD `ctime` DATETIME NOT NULL COMMENT '创建时间' AFTER `sap_status`;

                    $model_info = D("StockingInfo");
                    $sqlforItem  = "SELECT SUM(amout) as itemAmount, SUM(total_price) as itemTotalValue FROM `think_stocking_info` WHERE suppliers_code = '{$suppliersCode}' AND item_code = '{$itemCode}' and ctime BETWEEN '{$yesterdayTime}' AND '{$nowTime}'";
                    $result = $model_info->query($sqlforItem);
                    if (empty($result[0])){
                    }else{
                        $lastDatabyItemAndsuppliers = $result[0];
                        $tmpItemAmount = $itemAmount + $items[$itemCode]['available_inventory']+ $lastDatabyItemAndsuppliers['itemAmount'] ;
                        if($tmpItemAmount > $items[$itemCode]['r_inventory']){
                            // must
                            //var_dump('must 03');
                            $runProcessTag = 1;
                            break;
                        }
                    }

                    //20170523添加新判断规则: 如果备货数量<本次采购数量=$value['amout']>大于建议备货数量<$value['suggestorder']>时，则触发审批!by物料
                    $suggestOrder = $value['suggestorder'];
                    if ($itemAmount > $suggestOrder){
                        $runProcessTag = 1;
                        break;
                    }

                    //框架工作模式
                    //$model = D('StockingInfo');
                    //$data = $model->where("suppliers_code={$suppliersCode}","item_code={$itemCode}")->select();

                }

            }

            // 4. by 供应商 判定条件: 计算包括本次订单在内的，以当前时间为基准前溯过去24小时内，该供应商的订单总金额不超过5万，且货品总数量不超过1000个.
            if($runProcessTag == 0){
                $model = D("Stocking");
                $sqlforTotal  = "SELECT SUM(item_count) as itemTotal, SUM(price_total) as totalValue FROM `think_stocking` WHERE suppliers_code = '{$suppliersCode}' and ctime BETWEEN '{$yesterdayTime}' AND '{$nowTime}'";
                $result = $model->query($sqlforTotal);
                if (empty($result[0])){
                    // 2017-07-24 向前回退24小时没有满足触发条件的数据，但是当前订单数量，金额都已超限的情况。 $runProcessTag = 1;

                }else{
                    $lastDatabySuppliers = $result[0];
                    if ($lastDatabySuppliers['itemTotal'] > 1000 || $lastDatabySuppliers['totalValue'] > 50000){
                        //var_dump('must 04');
                        $runProcessTag = 1;
                    }
                }
            }

        }
        else{
            // 非常规，集采必审批
            $runProcessTag = 1;
        }
        
        if($id){
            $where = "stocking_id={$id}";
            $stData = array('receipterCode'=>$receipterCode, 'receipter'=>$receipter,'user'=>$user,'to_user'=>$stock_process[0],'item_count'=>$total,'price_total'=>$totalPrice,'remarkes'=>$remarkes,'suppliers_code'=>$suppliers_code,'suppliers_name'=>$suppliers_name,'type'=>$type,'stock_process'=>json_encode($stock_process,JSON_UNESCAPED_UNICODE),'storage_time'=>$storage_time);
            $model->where($where)->save($stData);
            $this->_saveLog(array('stocking_id'=>$id,'user'=>$user,'info'=>'修改'));
            $infoModel->where($where)->delete();
        }else{
            if ($runProcessTag == 0)
            {
                // status = 2
                // to_user = ''
                $stData = array('status'=>'2','receipterCode'=>$receipterCode, 'receipter'=>$receipter,'name'=>$name,'ctime'=>$nowTime,'user'=>$user,'to_user'=>$stock_process[0],'step'=>0,'item_count'=>$total,'price_total'=>$totalPrice,'remarkes'=>$remarkes,'suppliers_code'=>$suppliers_code,'suppliers_name'=>$suppliers_name,'type'=>$type,'stock_process'=>json_encode($stock_process,JSON_UNESCAPED_UNICODE),'manager'=>$cp,'sale'=>'','storage_time'=>$storage_time);
            }else {
                $stData = array('receipterCode' => $receipterCode, 'receipter' => $receipter, 'name' => $name, 'ctime' => $nowTime, 'user' => $user, 'to_user' => $stock_process[0], 'step' => 0, 'item_count' => $total, 'price_total' => $totalPrice, 'remarkes' => $remarkes, 'suppliers_code' => $suppliers_code, 'suppliers_name' => $suppliers_name, 'type' => $type, 'stock_process' => json_encode($stock_process, JSON_UNESCAPED_UNICODE), 'manager' => $cp, 'sale' => '', 'storage_time' => $storage_time);
            }

            $id = $model->add($stData);

            if ($runProcessTag == 0)
            {
                $this->_saveLog(array('stocking_id'=>$id,'user'=>$user,'info'=>'创建,并自动通过审核.'));
            }else {
                $this->_saveLog(array('stocking_id' => $id, 'user' => $user, 'info' => '创建'));
            }

        }
        
        /**
         * 添加物料明细
         */
        foreach ($saveData as $vo){
            unset($vo['id']);
            $vo['stocking_id']   = $id;
            $vo['storage_time']  = $storage_time;
            $vo['suppliers_name']= $suppliers_name;
            $vo['suppliers_code']= $suppliers_code;
            if (!empty($nowTime)){
                $vo['ctime']= $nowTime;
            }
            $infoModel->add($vo);
        }
        
        echo json_encode($respons);
        
    }
    
    /**
     * 检查物料选择的仓库有是否正确
     */
    function _checkItemWHCode($itemCode,$whcode){
    
        import("@.ORG.Util.Sqlserver");
        $sqlObj  = new Sqlserver();
        $sql = "select whscode, case WhsCode when 'A02' then '虚拟卡券仓'
when 'HYWCK' then '昆山实体仓'
when 'JDGD' then '京东光大仓'
when 'A07' then '样品仓'
end  FROM   OITW where itemcode='{$itemCode}' and whscode='{$whcode}' and  whscode  in   ('HYWCK','A02','JDGD','A07')";
        //$sql = "select whscode,whsname from ax_itemavailablewhs where itemcode='{$itemCode}' and whscode='{$whcode}'";
        $data = $sqlObj->query($sql);
       if($data)
           return true;
       else 
           return false;
    
    }
    
    
    
    function info(){
        $id = (int)I('id');
        $info = D('Stocking')->where("id={$id}")->find();
        if($info){

            // 2017-11-29 市场部要求：加急
            import("@.ORG.Util.SalesSupervisor");
            $salesSupervisorImpl = SalesSupervisor::getInstance();
            $allSalesArray = $salesSupervisorImpl->getSalesSupervisorListWithBoss();
            $empNo = session('emp_no');
            if (in_array($empNo,$allSalesArray)){
                $this->assign('urgentEnable',true);
            }else{
                $this->assign('urgentEnable',false);
            }
            
            if(strtolower(session('user_name'))==strtolower($info['to_user'])){
                $this->assign('access',true);
            }
            
            if($info['status']==2||$info['status']==-1){
                $this->assign('access',false);
            }
        }
        $this->assign('log',D('StockingLog')->where("pid={$id} and type='stocking'")->select());
        $this->assign('info',$info);
        $this->display();
    }
    
    function getinfo(){
         $id = (int)I('id');
         $model = D('StockingInfo');
         $data = $model->where("stocking_id={$id}")->select();
         $data = array('total'=>count($data),'data'=>$data);
         echo json_encode($data);
         exit;
    }

    function getinfoandexport(){
        $id = (int)I('id');
        $model = D('StockingInfo');
        $data = $model->where("stocking_id={$id}")->select();

        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, '物料号');
        $currentSheet->setCellValue('B'.$m, '物料名称');
        $currentSheet->setCellValue('C'.$m, '供应商');
        $currentSheet->setCellValue('D'.$m, '供应商编号');
        $currentSheet->setCellValue('E'.$m, '本次采购价格');
        $currentSheet->setCellValue('F'.$m, '上次采购价格');
        $currentSheet->setCellValue('G'.$m, '仓库');
        $currentSheet->setCellValue('H'.$m, '价格变动率(%)');
        $currentSheet->setCellValue('I'.$m, '申请备货数量');
        $currentSheet->setCellValue('J'.$m, '备货金额');
        $currentSheet->setCellValue('K'.$m, '建议安全库存');
        $currentSheet->setCellValue('L'.$m, '在库库存');
        $currentSheet->setCellValue('M'.$m, '在途库存');
        $currentSheet->setCellValue('N'.$m, '可用库存');
        $currentSheet->setCellValue('O'.$m, '到货日期');
        $currentSheet->setCellValue('P'.$m, '近15天销量');
        $currentSheet->setCellValue('Q'.$m, '前30天销量');
        $currentSheet->setCellValue('R'.$m, '累计销量');
        $currentSheet->setCellValue('S'.$m, '建议备货数量');
        $currentSheet->setCellValue('T'.$m, '可用库存天数');
        $currentSheet->setCellValue('U'.$m, '平均订货天数');
        $currentSheet->setCellValue('V'.$m, '平均日销量');
        $currentSheet->setCellValue('W'.$m, '最低安全库存');
        $currentSheet->setCellValue('X'.$m, '备注');

        $cellIndex=2;
        foreach ($data as $k => $v){

            $currentSheet->setCellValueExplicit('A'.$cellIndex,$v['item_code'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B'.$cellIndex,$v['item_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('C'.$cellIndex,$v['suppliers_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('D'.$cellIndex,$v['suppliers_code'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('E'.$cellIndex,$v['p_price'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('F'.$cellIndex,$v['previous_price'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('G'.$cellIndex,$v['warehouse'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('H'.$cellIndex,$v['change_price'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('I'.$cellIndex,$v['amout'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('J'.$cellIndex,$v['total_price'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('K'.$cellIndex,$v['r_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('L'.$cellIndex,$v['current_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('M'.$cellIndex,$v['transit_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('N'.$cellIndex,$v['available_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('O'.$cellIndex,$v['storage_time'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('P'.$cellIndex,$v['lately_15'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Q'.$cellIndex,$v['lately_30'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('R'.$cellIndex,$v['taotal_sales'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('S'.$cellIndex,$v['suggestorder'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('T'.$cellIndex,$v['availableday'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('U'.$cellIndex,$v['avgbuyday'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('V'.$cellIndex,$v['avgdaliysale'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('W'.$cellIndex,$v['minsafe'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('X'.$cellIndex,$v['remarks'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $cellIndex ++;
        }
        // 输出
        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }
    
    
    
    
    
    /**
     * 审核
     */
    function review(){
        $respons = array('code'=>0,'msg'=>'');
        $id = I('id');
        $status = I('status');
        $model =  D('Stocking');
        $info =$model->where("id={$id}")->find();
        $reviewstep = json_decode($info['stock_process'],true);
        if($info['step']==count($reviewstep)-1){ //完结 最后一个审核
            if($status!=-1)
                $status = 2;    
            $info['to_user'] = '';
            
        }else{
            $info['to_user'] = $reviewstep[$info['step']+1];
        }
        
        if($status==-1){
            $info['to_user'] = '';
        }
        $info['status'] = $status;
        $info['step']+=1; //当前审核步骤+1
        $remarkes = I('remarkes');
        $loginfo = $info['status']>=1?"同意":"否决";
        $this->_saveLog(array('stocking_id'=>$id,'user'=>session('user_name'),'info'=>$remarkes?$loginfo."  备注:".$remarkes:$loginfo));
        if($info['status']!=-1&&$info['status'] != 2&&$info['to_user']){
             $this->sendEmail($info['to_user'].'@g-town.com.cn', "有新的备货申请单等待您审核", "单号名称:{$info['name']}<br/>物料总数:{$info['item_count']}<br/>备货总价:{$info['price_total']}<br/>申请人:{$info['user']}");
             //weixinsendmsg("[有新的备货申请单等待您审核]", "单号名称:{$info['name']}\n物料总数:{$info['item_count']}\n备货总价:{$info['price_total']}\n申请人:{$info['user']} \n请及时登陆OA系统处理",  $info['to_user']);
        }
        if($status==-1) {
            // 不通过 : 向之前所有已审批通过的用户发送邮件通知：此单被XXX拒绝，拒绝理由：YYY
            $currentOperator = session('emp_no');
            foreach ($reviewstep as $key => $item)
            {
                if($item == $currentOperator)
                {
                    break;
                }else{
                    //echo $item." ";
                    //$userName = "maxwell.shi";
                    $this->sendEmail($item.'@g-town.com.cn', "备货申请单{$info['name']}未通过审核", "单号名称:{$info['name']}<br/>物料总数:{$info['item_count']}<br/>备货总价:{$info['price_total']}<br/>申请人:{$info['user']}<br/>未通过原因:{$remarkes}");
                }
            }
        }
        
        $model->where("id={$id}")->save($info);
        echo json_encode($respons);exit;


    }

    /**
     * @description: 加急
     * @date: 2017-11-29
     */
    function doUrgentEnable(){

        $respons = array('code'=>0,'msg'=>'');
        $id = I('id');
        $status = I('status');
        $stockingModel =  D('Stocking');
        $info =$stockingModel->where("id={$id}")->find();
        $info['is_urgent'] = $status;

        // Log
        $remarkes = I('remarkes');
        $loginfo = $info['status']>=1?"加急":"";
        $this->_saveLog(array('stocking_id'=>$id,'user'=>session('user_name'),'info'=>$remarkes?$loginfo."  备注:".$remarkes:$loginfo));
        // 暂不送出邮件

        $stockingModel->where("id={$id}")->save($info);
        echo json_encode($respons);exit;

    }

    
    /**
     * 保存操作日志
     * @param unknown $data
     * @return Ambigous <mixed, boolean, unknown, string>
     */
    function _saveLog($data = array()){
        return D('StockingLog')->add(array('pid'=>$data['stocking_id'],'user'=>$data['user'],'info'=>$data['info'],'ctime'=>date('Y-m-d H:i:s'),'type'=>'stocking'));
        
    }
    /**
     * 根据itemcode 获取物料其他信息
     */
    function getItemInfo(){
        $code = I('itemCode');
        import("@.ORG.Util.Sqlserver");
        $sqlObj  = new Sqlserver();
        $sql = "select itemcode, isnull(LastPurPrc,0) LastPurPrc  from oitm where itemcode='{$code}' ";
        $lastp_price = $sqlObj->query($sql)[0]['LastPurPrc'];
        //$sql = "select itemcode,onhand current_inventory ,onorder transit_inventory,onhand+onorder-U_TI_Z0_IsCommited-U_TI_Z0_IsJp  available_inventory from oitw where whscode in ('HYWCK') and itemcode='{$code}'";
        //2018-04-17 汇总仓库：'HYWCK','H03'数据: molly.
        $sql = "select itemcode,sum(onhand ) current_inventory ,sum(onorder) transit_inventory,sum(onhand+onorder-U_TI_Z0_IsCommited-U_TI_Z0_IsJp)  available_inventory from oitw where whscode in ('HYWCK','H03') and itemcode='{$code}' group by itemcode";
        $inventoryInfo =  $sqlObj->query($sql)[0];
        $sql = "SELECT [itemcode] ,[RsafeStock] r_inventory ,[Day7sales] lately_7 ,[Day15sales] lately_15 ,[Day30sales] lately_30 ,[Day365sales] taotal_sales,[suggestorder],[availableday],[avgbuyday],[avgdaliysale],[minsafe] FROM [dbo].[AX_SafeStockAndSalesCount] where itemcode='{$code}'";
        $saleInfo =  $sqlObj->query($sql)[0];
        $whouseSql  = "select whscode,whsname from ax_itemavailablewhs where itemcode='{$code}' order by whscode desc";
        $whouse =  $sqlObj->query($whouseSql)[0]['whscode'];
        $respons = array('warehouseCode'=>$whouse,'r_inventory'=>(int)$saleInfo['r_inventory'],'lately_7'=>(int)$saleInfo['lately_7'],'lately_15'=>(int)$saleInfo['lately_15'],'lately_30'=>(int)$saleInfo['lately_30'],'taotal_sales'=>(int)$saleInfo['taotal_sales'], 'previous_price'=>$lastp_price,'current_inventory'=>(int)$inventoryInfo['current_inventory'],'transit_inventory'=>(int)$inventoryInfo['transit_inventory'],'available_inventory'=>(int)$inventoryInfo['available_inventory'],'suggestorder'=>(int)$saleInfo['suggestorder'],'availableday'=>(int)$saleInfo['availableday'],'avgbuyday'=>(int)$saleInfo['avgbuyday'],'avgdaliysale'=>(int)$saleInfo['avgdaliysale'],'minsafe'=>(int)$saleInfo['minsafe']);
        echo json_encode($respons);
        exit;
        
    }

    protected function _getItemInfo($code) {
        import("@.ORG.Util.Sqlserver");
        $sqlObj  = new Sqlserver();
        $sql = "select itemcode, isnull(LastPurPrc,0) LastPurPrc  from oitm where itemcode='{$code}' ";
        $lastp_price = $sqlObj->query($sql)[0]['LastPurPrc'];
        $sql = "select itemcode,onhand current_inventory ,onorder transit_inventory,onhand+onorder-U_TI_Z0_IsCommited-U_TI_Z0_IsJp  available_inventory from oitw where whscode in ('HYWCK') and itemcode='{$code}'";
        $inventoryInfo =  $sqlObj->query($sql)[0];
        $sql = "SELECT [itemcode] ,[RsafeStock] r_inventory ,[Day7sales] lately_7 ,[Day15sales] lately_15 ,[Day30sales] lately_30 ,[Day365sales] taotal_sales,[suggestorder],[availableday],[avgbuyday],[avgdaliysale],[minsafe] FROM [dbo].[AX_SafeStockAndSalesCount] where itemcode='{$code}'";
        $saleInfo =  $sqlObj->query($sql)[0];
        $whouseSql  = "select whscode,whsname from ax_itemavailablewhs where itemcode='{$code}' order by whscode desc";
        $whouse =  $sqlObj->query($whouseSql)[0]['whscode'];
        $respons = array('warehouseCode'=>$whouse,'r_inventory'=>(int)$saleInfo['r_inventory'],'lately_15'=>(int)$saleInfo['lately_15'],'lately_30'=>(int)$saleInfo['lately_30'],'taotal_sales'=>(int)$saleInfo['taotal_sales'], 'previous_price'=>$lastp_price,'current_inventory'=>(int)$inventoryInfo['current_inventory'],'transit_inventory'=>(int)$inventoryInfo['transit_inventory'],'available_inventory'=>(int)$inventoryInfo['available_inventory'],'suggestorder'=>(int)$saleInfo['suggestorder'],'availableday'=>(int)$saleInfo['availableday'],'avgbuyday'=>(int)$saleInfo['avgbuyday'],'avgdaliysale'=>(int)$saleInfo['avgdaliysale'],'minsafe'=>(int)$saleInfo['minsafe']);
        return $respons;

    }
    
    function mystocking(){

        $key = I('keyword');
        $type = I('eq_type');
        $map=[];
        $user  = session('user_name');
        if($type=='-8'){
            $map['concat(stock_process,user)'] = array('like',  '%' . trim($user) . '%');
        }
        else
        $map['concat(to_user,user)'] = array('like',  '%' . trim($user) . '%');
        
        if(isset($_POST['type'])||$type){
                if($type!='-8')
                $map['status'] = array('eq', $type);
        }else{
            $map['status'] = array('eq', 1);
        }
        
        if($key){
            $map['concat(name,sap_code,suppliers_name)'] = array('like',  '%' . trim($key) . '%');
        }
        $model = M("Stocking");
        $this->assign('curr_user',session('user_name'));
        $this->assign('keyword',$key);
        $this->assign('status',$type?:1);
        $res= $this -> _list($model, $map, 'id desc');
        $this->display();
        
    }

    function getBuyer(){
        $type = (int)I('type');

        $userlist = array();
        switch ($type){
            case 1:
                $model = D("gtBuyer");
                $filed = ('*');
                $userlist = $model->field($filed)->where('the_role != 3')->select();
                break;
            default:
                break;
        }
        $tempList = array();
        foreach ($userlist as $key=>$vo){
            $tempList[$key]['id'] = $vo['emp_no'];
            $tempList[$key]['text'] = $vo['emp_no'];
        }
        echo json_encode($tempList);
        exit;
    }
    
    function getUser(){
        $type = (int)I('type');
//        $chanpin = "wendy.li,mario,dem,denny,jiang,baden,taylor,vicky,kai,lucy,sindy,sara,missy,mani,maggie,catherine,abyss,daisy,archer";
//        $sale    = "dem,mutt,yina,sue,zora,makaveli,echo,abby,louise,lily,sammi,scarlett,angela,rebecca,vivian,carrie";
        //创建新表:product_manager,sales_supervisor
        $userlist = array();
        switch ($type){
            case 1:
                $model = D("product_manager");
                $filed = ('*');
                $userlist = $model->field($filed)->group('emp_no')->select();
//                $userlist = explode(',', $chanpin);
                break;
            default:
                $model = D("sales_supervisor");
                $filed = ('*');
                $userlist = $model->field($filed)->select();
//                $userlist = explode(',', $sale);
                break;
        }
        $tempList = array();
        foreach ($userlist as $key=>$vo){
            $tempList[$key]['id'] = $vo['emp_no'];
            $tempList[$key]['text'] = $vo['emp_no'];
        }
        echo json_encode($tempList);
        exit;
    }
    
    function getreceipter(){
        import("@.ORG.Util.Sqlserver");
        $sqlObj  = new Sqlserver();
        $sql = "select slpcode,SlpName from oslp";
        $info =  $sqlObj->query($sql);
        echo json_encode($info);
    }

    function manageps(){
        $this->display();
    }

    function listProductManager(){
        $productManagerModel = M("ProductManager");
        $result = $productManagerModel->order("captain_no desc")->select();
        echo json_encode($result);
    }

    function updateProductManager(){
        $productManagerModel = M("ProductManager");
        $data = json_decode(I('data'), 1);
        foreach ($data as $key => $rowData){
            if ($rowData['_state'] == "removed"){
                $productManagerModel->where("id = {$rowData['id']}")->delete();
            }
            if ($rowData['_state'] == "added"){
                $productManagerModel->add($rowData);
            }
            if ($rowData['_state'] == "modified"){
                $productManagerModel->save($rowData);
            }
        }
    }

    function listSalesSupervisor(){
        $productManagerModel = M("SalesSupervisor");
        $result = $productManagerModel->order("id desc")->select();
        echo json_encode($result);
    }

    function updateSalesSupervisor(){
        $productManagerModel = M("SalesSupervisor");
        $data = json_decode(I('data'), 1);
        foreach ($data as $key => $rowData){
            if ($rowData['_state'] == "removed"){
                $productManagerModel->where("id = {$rowData['id']}")->delete();
            }
            if ($rowData['_state'] == "added"){
                $productManagerModel->add($rowData);
            }
            if ($rowData['_state'] == "modified"){
                $productManagerModel->save($rowData);
            }
        }
    }
    
}